// ./src/main/java/org/mms/service/impl/TransportationServiceImpl.java
package org.mms.service.impl;

import org.mms.exception.BusinessException;
import org.mms.pojo.entity.Transportation;
import org.mms.pojo.entity.Vehicle; // 引入 Vehicle
import org.mms.pojo.request.TransportationRequest;
import org.mms.repository.TransportationRepository;
import org.mms.repository.VehicleRepository; // 引入 VehicleRepository
import org.mms.service.TransportationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; // 引入 Transactional

import java.util.List;
import java.util.Objects; // 引入 Objects

@Service
public class TransportationServiceImpl implements TransportationService {

    @Autowired
    private TransportationRepository transportationRepository;
    @Autowired
    private VehicleRepository vehicleRepository; // 注入 VehicleRepository

    @Override
    public List<Transportation> list() {
        return transportationRepository.findAll();
    }

    @Override
    public Transportation getById(Long id) {
        return transportationRepository.findById(id)
                .orElseThrow(() -> new BusinessException("运输记录不存在 (ID: " + id + ")"));
    }

    @Override
    @Transactional // 保证原子性操作
    public Transportation create(TransportationRequest request) {
        if (request.getVehicleId() == null) {
            throw new BusinessException("必须选择车辆");
        }
        Vehicle vehicle = vehicleRepository.findById(request.getVehicleId())
                .orElseThrow(() -> new BusinessException("选择的车辆不存在 (ID: " + request.getVehicleId() + ")"));

        if (!vehicle.isAvailable()) {
            throw new BusinessException("车辆 '" + vehicle.getLicensePlate() + "' 当前状态为 '" + vehicle.getStatus() + "', 不可用");
        }

        Transportation entity = new Transportation();
        BeanUtils.copyProperties(request, entity, "id");
        entity.setVehicle(vehicle);

        vehicle.setStatus(Vehicle.STATUS_IN_USE);
        vehicleRepository.save(vehicle);

        return transportationRepository.save(entity);
    }

    @Override
    @Transactional // 保证原子性操作
    public Transportation update(TransportationRequest request) {
        if (request.getId() == null) {
            throw new BusinessException("更新运输记录必须提供ID");
        }
        if (request.getVehicleId() == null) {
            throw new BusinessException("必须选择车辆");
        }

        Transportation entity = transportationRepository.findById(request.getId())
                .orElseThrow(() -> new BusinessException("运输记录不存在 (ID: " + request.getId() + ")"));

        Vehicle oldVehicle = entity.getVehicle(); // 获取旧车辆
        Vehicle newVehicle = vehicleRepository.findById(request.getVehicleId())
                .orElseThrow(() -> new BusinessException("选择的新车辆不存在 (ID: " + request.getVehicleId() + ")"));

        boolean vehicleChanged = !Objects.equals(oldVehicle.getId(), newVehicle.getId());
        if (vehicleChanged && newVehicle.isAvailable()) {
            throw new BusinessException("新选择的车辆 '" + newVehicle.getLicensePlate() + "' 当前状态为 '" + newVehicle.getStatus() + "', 不可用");
        }

        entity.setDestination(request.getDestination());
        entity.setVehicle(newVehicle);

        if (vehicleChanged) {
            oldVehicle.setStatus(Vehicle.STATUS_AVAILABLE);
            vehicleRepository.save(oldVehicle);

            newVehicle.setStatus(Vehicle.STATUS_IN_USE);
            vehicleRepository.save(newVehicle);
        }
        return transportationRepository.save(entity);
    }

    @Override
    @Transactional // 保证原子性操作
    public void delete(Long id) {
        Transportation entity = transportationRepository.findById(id)
                .orElseThrow(() -> new BusinessException("运输记录不存在 (ID: " + id + ")"));

        Vehicle vehicle = entity.getVehicle();
        if (vehicle != null) {
            if (Objects.equals(vehicle.getStatus(), Vehicle.STATUS_IN_USE)) {
                vehicle.setStatus(Vehicle.STATUS_AVAILABLE);
                vehicleRepository.save(vehicle);
            }
        }

        transportationRepository.deleteById(id);
    }
}